package open.tech.dawn.core.base;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import open.tech.dawn.core.error.ServiceException;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Data
@Slf4j
public class BaseDto {

    /**
     * 空值校验
     */
    public void emptyValid() {
        Field[] fields = ReflectUtil.getFields(getClass());
        if (fields == null || fields.length == 0)
            return;
        for (Field field : fields) {
            DtoEmptyValid dtoEmptyValid = field.getAnnotation(DtoEmptyValid.class);
            if (dtoEmptyValid == null)
                continue;
            String message = dtoEmptyValid.message();
            String name = field.getName();
            if (StrUtil.isEmpty(message) || message.trim().isEmpty()) {
                message = name + "数据为空";
            }
            String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = ReflectUtil.getMethod(getClass(), methodName, field.getType());
            Object invoke = null;
            if (method == null) {
                try {
                    field.setAccessible(true);
                    invoke = field.get(this);
                } catch (Exception e) {
                    log.error("校验Dto对象异常", e);
                }
            } else {
                try {
                    invoke = method.invoke(this);
                } catch (Exception e) {
                    log.error("校验Dto对象异常", e);
                }
            }
            if (invoke == null) {
                throw new ServiceException(message);
            }
            if (invoke instanceof String) {
                String s = (String) invoke;
                s = s.trim();
                if (StrUtil.isEmpty(s)) {
                    throw new ServiceException(message);
                }
                //规则校验
                String rule = dtoEmptyValid.rule();
                if (StrUtil.isNotEmpty(rule)) {
                    if (!s.matches(rule)) {
                        throw new ServiceException(dtoEmptyValid.ruleMessage());
                    }
                }
            }

        }
    }

}
